<template>
  <div ref="appContainer" class="app-container home-bg-padding">
    <!-- 查询部分 -->
    <CustomSearch
      ref="searchForm"
      :show-all.sync="showAll"
      @search="searchFn"
      @reset="resetFn"
    >
      <template #btns>
        <sec-button type="primary" icon="sec-icon-bianji" @click="addDict"
          >新增</sec-button
        >
        <sec-button
          type="danger"
          icon="sec-icon-shanchu"
          :disabled="selectedDict.idArray.length === 0"
          @click="deleteSelectedDict"
          >删除</sec-button
        >
        <sec-tooltip
          class="item"
          effect="dark"
          content="刷新"
          placement="top-start"
        >
          <sec-button
            icon="sec-icon-shuaxin"
            circle
            @click="updateList()"
          ></sec-button>
        </sec-tooltip>
      </template>
      <template #search>
        <sec-input
          v-model="searchForm.description"
          class="search-input"
          size="medium"
          placeholder="请输入字典名称"
          suffix-icon="sec-icon-sousuo"
          style="width: 300px"
          clearable
        />
      </template>
      <template #select>
        <sec-form-item prop="type">
          <sec-input
            v-model="searchForm.type"
            class="search-input"
            size="medium"
            placeholder="请输入字典类型"
            clearable
          />
        </sec-form-item>
        <sec-form-item prop="dateTime" class="search-form-40">
          <sec-date-picker
            v-model="searchForm.dateTime"
            type="datetimerange"
            size="middle"
            format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            @change="changeDate"
          >
          </sec-date-picker>
        </sec-form-item>
      </template>
    </CustomSearch>

    <!-- 表格部分 -->
    <div class="query-table">
      <sec-table
        :data="dictList"
        size="mini"
        style="width: 100%; height: calc(100% - 42px); overflow-y: scroll"
        stripe
        @selection-change="handleSelectionChange"
      >
        <sec-table-column
          fixed
          type="selection"
          align="center"
          width="50"
        ></sec-table-column>
        <sec-table-column
          prop="index"
          label="序号"
          align="center"
          width="80"
        ></sec-table-column>
        <sec-table-column
          prop="description"
          label="字典名称"
          align="center"
        ></sec-table-column>
        <sec-table-column
          prop="type"
          label="字典类型"
          align="center"
        ></sec-table-column>
        <sec-table-column
          prop="remark"
          label="备注"
          align="center"
        ></sec-table-column>
        <sec-table-column fixed="right" label="操作" align="center" width="170">
          <template slot-scope="scope">
            <sec-button
              type="text"
              size="small"
              icon="sec-icon-bianji"
              @click="detailDict(scope.row)"
              >详情</sec-button
            >
            <sec-button
              type="text"
              size="small"
              icon="sec-icon-bianji"
              @click="editDict(scope.row)"
              >编辑</sec-button
            >
            <sec-button
              type="text"
              size="small"
              icon="el-icon-delete"
              @click="deleteDict(scope.row)"
              >删除</sec-button
            >
          </template>
        </sec-table-column>
      </sec-table>
      <div class="pagination">
        <sec-pagination
          :current-page.sync="pagination.pageNo"
          :page-size="pagination.pageSize"
          layout="total,prev, pager, next,sizes"
          :total="pagination.totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></sec-pagination>
      </div>
    </div>

    <!-- 新增/编辑/详情抽屉部分 -->
    <sec-drawer
      size="800px"
      :visible.sync="formVisible"
      :title="drawerTitle"
      :modal="true"
      :before-close="handleDialogClose"
      custom-class="drawer-detail-form asset-add"
      :wrapper-closable="true"
    >
      <div class="drawer-container drawer-container-add">
        <sec-form
          v-if="drawerType === 0 || drawerType === 1"
          ref="formRef"
          :model="form"
          class="search-bar-form search-form-50"
          label-width="130px"
          label-suffix=":"
          :rules="formRules"
        >
          <sec-form-item
            label="字典名称"
            prop="description"
            style="margin-right: 100px"
          >
            <sec-input
              v-model="form.description"
              size="medium"
              placeholder="请输入字典名称"
            ></sec-input>
          </sec-form-item>
          <sec-form-item
            label="字典类型"
            prop="type"
            style="margin-right: 100px"
          >
            <sec-input
              v-model="form.type"
              size="medium"
              placeholder="请输入字典类型"
            ></sec-input>
          </sec-form-item>
          <sec-form-item label="备注" prop="remark" style="margin-right: 100px">
            <sec-input
              v-model="form.remark"
              type="textarea"
              size="medium"
              placeholder="请输入内容"
            ></sec-input>
          </sec-form-item>
        </sec-form>

        <DetailTable
          v-else-if="drawerType === 2"
          :id="detailId"
          ref="detailTable"
          :type="detailType"
        />
        <div style="height: 50px">
          <span slot="footer" class="dialog-footer">
            <sec-button @click="handleDialogClose">取消</sec-button>
            <sec-button type="primary" @click="submit">确定</sec-button>
          </span>
        </div>
      </div>
    </sec-drawer>
  </div>
</template>

<script>
import CustomSearch from '@/components/CustomSearch'
import DetailTable from './components/detailTable'
import { cloneDeep } from 'lodash'
import moment from 'moment'
import pagination from '@/utils/mixins/pagination'
import http from '@/utils/http'
export default {
  components: { CustomSearch, DetailTable },
  mixins: [pagination],
  data() {
    return {
      showAll: true,
      searchForm: {
        type: '',
        startTime: '',
        endTime: ''
      },
      dictList: [],
      detailId: '',
      detailType: '',
      selectedDict: {
        idArray: []
      },
      drawerType: 0,
      formVisible: false,
      emptyForm: {
        description: '',
        type: '',
        remark: ''
      },
      form: {
        description: '',
        type: '',
        remark: ''
      },
      formRules: {
        description: [
          { required: true, message: '请输入字典名称', trigger: 'change' }
        ],
        type: [{ required: true, message: '请输入字典类型', trigger: 'change' }]
      }
    }
  },
  computed: {
    drawerTitle() {
      switch (this.drawerType) {
        case 0:
          return '添加字典类型'
        case 1:
          return '修改字典类型'
        case 2:
          return '字典详情'
      }
      return ''
    }
  },
  methods: {
    formatTime(val) {
      return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ''
    },
    msg(message, type) {
      this.$message({ message, type })
    },
    // 新增字典
    addDict() {
      this.drawerType = 0
      this.formVisible = true
    },
    // 删除选中字典
    deleteSelectedDict() {
      this.$confirm('<div>确认删除所有选中的字典?</div>', '提示', {
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(async () => {
        const { code } = await http.deleteDictIdsVo(this.selectedDict)
        if (code === '200') {
          this.msg('批量删除成功！', 'success')
          this.updateList()
        } else {
          this.msg('批量删除失败！', 'warning')
        }
      })
    },
    // 时间筛选事件范围修改
    changeDate(date) {
      const [startTime, endTime] = date
      this.searchForm.startTime = this.formatTime(startTime)
      this.searchForm.endTime = this.formatTime(endTime)
    },
    // 获取字典列表
    async getList(params) {
      // TODO
      try {
        const { data } = await http.getDictVoList(params)
        this.dictList = data?.rows || []
        this.pagination = {
          ...this.pagination,
          pageNo: params?.pageNo || 1,
          pageSize: data?.pageSize || 10,
          totalCount: data?.totalRows || 0
        }
        this.dictList.forEach((item, index) => {
          item.index =
            this.pagination.pageSize * (this.pagination.pageNo - 1) + index + 1
        })
      } catch (e) {
        console.error(e)
      }
    },
    // 编辑字典
    editDict(row) {
      this.drawerType = 1
      this.formVisible = true
      this.form = row
    },
    // 删除字典
    deleteDict(row) {
      this.$confirm('<div>确认删除所选字典?</div>', '提示', {
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(async () => {
        try {
          const { code } = await http.deleteDictVo({ id: row.id })
          if (code === '200') {
            this.msg('删除成功！', 'success')
            this.updateList()
          } else {
            this.msg('删除失败！', 'warning')
          }
        } catch (e) {
          console.error(e)
        }
      })
    },
    // 字典详情
    async detailDict(row) {
      this.drawerType = 2
      this.detailId = row.id
      this.detailType = row.type
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.detailTable.updateList()
      })
    },
    // 多选
    handleSelectionChange(val) {
      this.selectedDict.idArray = val.map((item) => {
        return item.id
      })
    },
    // 关闭抽屉
    handleDialogClose() {
      this.formVisible = false
      this.form = cloneDeep(this.emptyForm)
      this.detailList = []
      if (this.drawerType === 2) {
        this.$refs.detailTable.editableDetailData = {
          editRow: null,
          isEdit: false,
          isAdd: false
        }
      }
    },
    // 提交新增/编辑/详情编辑
    async submit() {
      if (this.drawerType === 2) {
        this.handleDialogClose()
      } else {
        this.$refs.formRef.validate(async (valid) => {
          if (valid) {
            if (this.drawerType === 0) {
              try {
                const { code } = await http.addDictVo(this.form)
                if (code === '200') {
                  this.msg('新增字典成功！', 'success')
                } else {
                  this.msg('新增字典失败！', 'warning')
                }
              } catch (e) {
                console.error(e)
              }
            } else if (this.drawerType === 1) {
              try {
                const { code } = await http.editDictVo(this.form)
                if (code === '200') {
                  this.msg('编辑字典成功！', 'success')
                } else {
                  this.msg('编辑字典失败！', 'warning')
                }
              } catch (e) {
                console.error(e)
              }
            }
            this.handleDialogClose()
            this.updateList()
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.item {
  width: 30px;
}
.drawer-container-add {
  .type-radio {
    margin: 0px 27px 24px;
  }

  .dialog-footer {
    width: 800px;
    text-align: right;
    display: block;
    position: fixed;
    right: 0;
    bottom: 0;
    padding: 8px 16px;
    border-top: 1px solid #f0f0f0;
    background-color: #ffffff;
  }
}
.pagination {
  text-align: right;
}
.app-container {
  display: flex;
  .query-table {
    background-color: #ffffff;
    flex: 1;
    height: 1%;
  }
}
</style>
